package com.imut.lagain.repository;

import com.imut.lagain.entity.ThoughtAnalysis;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 思维分析数据访问层
 */
@Mapper
public interface ThoughtAnalysisRepository extends BaseMapper<ThoughtAnalysis> {

    /**
     * 根据用户ID查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND is_deleted = 0 ORDER BY created_at DESC")
    List<ThoughtAnalysis> findByUserId(@Param("userId") Long userId);

    /**
     * 根据用户ID和会话ID查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND session_id = #{sessionId} AND is_deleted = 0 ORDER BY created_at DESC")
    List<ThoughtAnalysis> findByUserIdAndSessionId(@Param("userId") Long userId, @Param("sessionId") Long sessionId);

    /**
     * 根据用户ID和分析类型查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND analysis_type = #{analysisType} AND is_deleted = 0 ORDER BY created_at DESC")
    List<ThoughtAnalysis> findByUserIdAndAnalysisType(@Param("userId") Long userId, @Param("analysisType") String analysisType);

    /**
     * 根据用户ID和状态查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND status = #{status} AND is_deleted = 0 ORDER BY created_at DESC")
    List<ThoughtAnalysis> findByUserIdAndStatus(@Param("userId") Long userId, @Param("status") String status);

    /**
     * 根据用户ID和日期范围查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND created_at BETWEEN #{startDate} AND #{endDate} AND is_deleted = 0 ORDER BY created_at DESC")
    List<ThoughtAnalysis> findByUserIdAndDateRange(@Param("userId") Long userId, 
                                                   @Param("startDate") LocalDateTime startDate, 
                                                   @Param("endDate") LocalDateTime endDate);

    /**
     * 根据分析ID查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE id = #{analysisId} AND is_deleted = 0")
    ThoughtAnalysis findByAnalysisId(@Param("analysisId") Long analysisId);

    /**
     * 统计用户分析次数
     */
    @Select("SELECT COUNT(*) FROM thought_analysis WHERE user_id = #{userId} AND is_deleted = 0")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 统计用户在指定日期范围内的分析次数
     */
    @Select("SELECT COUNT(*) FROM thought_analysis WHERE user_id = #{userId} AND created_at BETWEEN #{startDate} AND #{endDate} AND is_deleted = 0")
    Long countByUserIdAndDateRange(@Param("userId") Long userId, 
                                   @Param("startDate") LocalDateTime startDate, 
                                   @Param("endDate") LocalDateTime endDate);

    /**
     * 统计用户不同分析类型的次数
     */
    @Select("SELECT analysis_type, COUNT(*) as count FROM thought_analysis WHERE user_id = #{userId} AND is_deleted = 0 GROUP BY analysis_type")
    List<Map<String, Object>> countByUserIdGroupByAnalysisType(@Param("userId") Long userId);

    /**
     * 查询用户最近的思维分析
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND is_deleted = 0 ORDER BY created_at DESC LIMIT 1")
    ThoughtAnalysis findLatestByUserId(@Param("userId") Long userId);

    /**
     * 查询用户最有效的思维分析（根据效果评分）
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND effectiveness_rating IS NOT NULL AND is_deleted = 0 ORDER BY effectiveness_rating DESC LIMIT 1")
    ThoughtAnalysis findMostEffectiveByUserId(@Param("userId") Long userId);

    /**
     * 更新思维分析状态
     */
    @Update("UPDATE thought_analysis SET status = #{status}, updated_at = NOW() WHERE id = #{id} AND is_deleted = 0")
    int updateStatus(@Param("id") Long id, @Param("status") String status);

    /**
     * 更新思维分析效果评分
     */
    @Update("UPDATE thought_analysis SET effectiveness_rating = #{rating}, anxiety_before = #{anxietyBefore}, anxiety_after = #{anxietyAfter}, updated_at = NOW() WHERE id = #{id} AND is_deleted = 0")
    int updateEffectiveness(@Param("id") Long id, 
                           @Param("rating") Integer rating, 
                           @Param("anxietyBefore") Integer anxietyBefore, 
                           @Param("anxietyAfter") Integer anxietyAfter);

    /**
     * 软删除思维分析记录
     */
    @Update("UPDATE thought_analysis SET is_deleted = 1, deleted_at = NOW() WHERE id = #{id}")
    int deleteById(@Param("id") Long id);

    /**
     * 分页查询用户思维分析记录
     */
    IPage<ThoughtAnalysis> selectPageByUserId(Page<ThoughtAnalysis> page, @Param("userId") Long userId);
    
    /**
     * 根据用户ID和洞察类型查询思维分析记录
     */
    @Select("SELECT * FROM thought_analysis WHERE user_id = #{userId} AND insights LIKE CONCAT('%', #{insightType}, '%') AND is_deleted = 0 ORDER BY created_at DESC")
    List<ThoughtAnalysis> findByUserIdAndInsightType(@Param("userId") Long userId, @Param("insightType") String insightType);
    
    /**
     * 查询指定时间范围内用户焦虑变化趋势
     */
    @Select("SELECT DATE(created_at) as date, AVG(anxiety_before) as avgBefore, AVG(anxiety_after) as avgAfter FROM thought_analysis WHERE user_id = #{userId} AND created_at BETWEEN #{startDate} AND #{endDate} AND anxiety_before IS NOT NULL AND anxiety_after IS NOT NULL AND is_deleted = 0 GROUP BY DATE(created_at) ORDER BY date")
    List<Map<String, Object>> findAnxietyTrendByUserIdAndDateRange(@Param("userId") Long userId, 
                                                                  @Param("startDate") LocalDateTime startDate, 
                                                                  @Param("endDate") LocalDateTime endDate);
}